<?php
namespace isoftstone\ueditor;

use Flarum\Http\Controller\ControllerInterface;
use Flarum\Settings\SettingsRepositoryInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Flarum\Foundation\Application;
use isoftstone\ueditor\FileUploader;

class ResourceController implements ControllerInterface
{

    protected $fileExt = [
        "bmp"=>"application/x-bmp",
        "css"=>"text/css",
        "htm"=>"text/html",
        "html"=>"text/html",
        "ico"=>"application/x-ico",
        "jpeg"=>"image/jpeg",
        "jpg"=>"application/x-jpg",
        "js"=>"application/x-javascript",
        "mp2v"=>"video/mpeg",
        "mp3"=>"audio/mp3",
        "mp4"=>"video/mpeg4",
        "mpeg"=>"video/mpg",
        "pdf"=>"application/pdf",
        "png"=>"application/x-png",
        "svg"=>"text/xml",
        "swf"=>"application/x-shockwave-flash",
        "tif"=>"application/x-tif",
        "tiff"=>"image/tiff",
        "wav"=>"audio/wav",
        "wax"=>"audio/x-ms-wax",
        "wma"=>"audio/x-ms-wma",
        "wmf"=>"application/x-wmf",
        "wmv"=>"video/x-ms-wmv",
    ];

    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;
    protected $app;

    /**
     * TestController constructor.
     * @param SettingsRepositoryInterface $settings
     */
    public function __construct(SettingsRepositoryInterface $settings, Application $app)
    {
        $this->settings = $settings;
        $this->app = $app;
    }

    /**
     * @param Request $request
     * @return string
     */
    public function handle(Request $request)
    {
        $path = array_get($request->getQueryParams(), 'path');
        $file = dirname(dirname(__FILE__)) . '/resource/' . $path;
        $type = $this->fileExt[pathinfo($file, PATHINFO_EXTENSION)];
        $file_name = basename($file);
        //判断给定的文件格式存在与否
        if($type==''){
            die("您要下载的文件格式不存在，可能是被删除");
        }
        //判断给定的文件存在与否
        if(!file_exists($file)){
            die("您要下载的文件已不存在，可能是被删除");
        }

        if($type=='text/html'){
            echo file_get_contents($file);
            exit;
        }
        header("Content-type:".$type.";charset=utf-8");
        $fp = fopen($file,"r");
        $file_size = filesize($file);
        //下载文件需要用到的头
        header("Accept-Ranges: bytes");
        header("Accept-Length:".$file_size);
        header("Content-Disposition: attachment; filename=".$file_name);
        $buffer = 10240;
        $file_count = 0;
        //向浏览器返回数据
        while(!feof($fp) && $file_count < $file_size){
            $file_con = fread($fp,$buffer);
            $file_count += $buffer;
            echo $file_con;
        }
        fclose($fp);
        exit;
    }

}
